package com.wngbms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {

    volatile static boolean start = true;

    public static void main(String[] args) throws IOException {

        ServerSocket server = null;
        server = new ServerSocket();
        server.bind(new InetSocketAddress("localhost", 8888));
        server.setReceiveBufferSize(10);
        server.setReuseAddress(false);
        server.setSoTimeout(0);

        System.out.println("server start at 8888");

        while (start) {
            System.in.read();

            System.out.println("begin accept");
            Socket client = server.accept();

            client.setKeepAlive(false);
            client.setOOBInline(false);
            client.setReceiveBufferSize(20);
            client.setReuseAddress(false);
            client.setSendBufferSize(20);
            client.setSoLinger(true, 0);
            client.setSoTimeout(0);
            client.setTcpNoDelay(false);

            new Thread(() -> {
                try {
                    InputStream in = client.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    char[] data = new char[1024];

                    while (true) {
                        int num = reader.read(data);
                        if (num > 0) {
                            System.out.println("client read some data is : " + num + " val : " + new String(data, 0, num));
                        } else if (num == 0) {
                            System.out.println("client read nothing");
                        } else {
                            System.out.println("read -1");
                            client.close();
                            break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }).start();
        }
    }

}
